﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using XMK.Tadong.Biz;
using XMK.Tadong.Model;
using System.Configuration;
using System.Data;
using ICSharpCode.SharpZipLib.Zip;

namespace XMK.Tadong.Web.WebFileExplorer.WebServices
{
    public partial class Download1 : System.Web.UI.Page
    {
        public string strTmpDir = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "Temp\\";
        public string strTmpDirZip = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "TempZip\\";
        string sourcepath = ConfigurationManager.AppSettings["DiskPath"];
        protected void Page_Load(object sender, EventArgs e)
        {
            //fileToZip();
            string spacetype = Request.QueryString["spacetype"];//
            string fileId = Request.QueryString["filePath"];
            
            if (spacetype == "project")
            {
                Tb_Xmk_FileBiz fileBiz = new Tb_Xmk_FileBiz();
                TB_XMK_FILEInfo fileInfo1 = fileBiz.QueryById(fileId);
                string fileName = fileInfo1.FILE_NAME;
                //string fileName = filePath.Substring(filePath.LastIndexOf('/') + 1); //客户端保存的文件名
                string filePath = fileInfo1.SAVE_PATH;
                string modelPath = ConfigurationManager.AppSettings["DiskPath"];
                filePath = modelPath + filePath;
                //string filepath = ConfigurationManager.AppSettings.Get("DiskPath") + fileInfo1.SAVE_PATH + "/" + fileInfo1.FILE_NAME;

                FileInfo fileInfo = new FileInfo(filePath);
                fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);

                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();

                Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                Response.WriteFile(fileInfo.FullName);
                Response.Flush();
                Response.End();



            }

            else if (spacetype == "group")
            {
                string fileid = Request.QueryString["filePath"];//文件id
                TB_TEAM_FILEBiz fileBiz = new TB_TEAM_FILEBiz();
                TB_TEAM_FILEInfo fileinfo = fileBiz.GetTeamFile(fileid);
                string fileName = fileinfo.FILE_NAME;
                //string fileName = filePath.Substring(filePath.LastIndexOf('/') + 1); //客户端保存的文件名
                string filePath = fileinfo.SAVE_PATH;
                string modelPath = ConfigurationManager.AppSettings["DiskPath"];
                filePath = modelPath + filePath;
                FileInfo fileInfo = new FileInfo(filePath);
                fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);

                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();

                Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                Response.WriteFile(fileInfo.FullName);
                Response.Flush();
                Response.End();
            }
            else if (spacetype == "individual")
            {
                string fileid = Request.QueryString["filePath"];//文件id
                TB_PERSON_FILEBiz fileBiz = new TB_PERSON_FILEBiz();
                DataTable fileinfo = fileBiz.GetModelList(fileid);
                string fileName = "";
                string filePath = "";
                for (int i = 0; i < fileinfo.Rows.Count; i++)
                {
                    fileName = fileinfo.Rows[i]["FILE_NAME"].ToString();
                    //string fileName = filePath.Substring(filePath.LastIndexOf('/') + 1); //客户端保存的文件名
                    filePath = fileinfo.Rows[i]["SAVE_PATH"].ToString();
                    if (!Directory.Exists(strTmpDir))
                    {
                        Directory.CreateDirectory(strTmpDir);
                    }
                    File.Copy(sourcepath + filePath, strTmpDir + fileName);
                }
                string modelPath = ConfigurationManager.AppSettings["DiskPath"];
                filePath = modelPath + filePath;
                FileInfo fileInfo = new FileInfo(filePath);
                fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);

                //临时文件存放
                if (!Directory.Exists(strTmpDir))
                {
                    Directory.CreateDirectory(strTmpDir);
                }
                //zip文件存放
                if (!Directory.Exists(strTmpDirZip))
                {
                    Directory.CreateDirectory(strTmpDirZip);
                }

                //保存文件的名称
                string strZipFileName = strTmpDirZip + System.DateTime.Now.ToString("yyyyMMddhhssmm") + ".zip";

                string[] filenames = Directory.GetFiles(strTmpDir);
                //删除文件
                try
                {
                    if (File.Exists(strZipFileName))
                        File.Delete(strZipFileName);
                }
                catch
                {
                    //删除文件失败时（例如该文件正在使用中）不做任何操作
                }
                ZipOutputStream u = new ZipOutputStream(File.Create(strZipFileName));
                u.SetLevel(9);
                foreach (string file in filenames)
                {
                    FileStream fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    //获取文件名称，注意不带路径，这样压缩后文件不带路径目录
                    string[] names = file.Split('\\');

                    string file1 = names[names.Length - 1];

                    ZipEntry entry = new ZipEntry(file1);

                    u.PutNextEntry(entry);

                    u.Write(buffer, 0, buffer.Length);
                    fs.Close();
                    fs.Dispose();
                    
                    File.Delete(file);
                }
                u.Finish();
                u.Close();
                u.Dispose();
                //Directory.Delete(strTmpDir);
                //下载传输文件
                ReponseFile(strZipFileName);
            }
        }

        /// <summary>
        /// Reponse出文件
        /// </summary>
        /// <param name="strFileName"></param>
        public void ReponseFile(string strFileName)
        {

            string[] names = strFileName.Split('/');

            //返回文件
            string strHttpFilePath = "";
            strHttpFilePath = "http://" + System.Web.HttpContext.Current.Request.Url.Host + ":" + System.Web.HttpContext.Current.Request.Url.Port + System.Web.HttpContext.Current.Request.ApplicationPath + "/Temp/" + names[names.Length - 1].ToString().Trim();
            
            System.Web.HttpContext.Current.Response.Write("<script language='javascript'>window.open('" + strHttpFilePath + "','_blank');</script>");
        }
    }
}